package com.dragee.modules.work.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dragee.common.PageUtils;
import com.dragee.common.R;
import com.dragee.config.exception.BusinessException;
import com.dragee.modules.base.entity.DicEntity;
import com.dragee.modules.base.service.DicService;
import com.dragee.modules.sys.entity.UserEntity;
import com.dragee.modules.sys.service.UserService;
import com.dragee.modules.work.dto.JoinPayInfoExport;
import com.dragee.modules.work.dto.JoinPersonsExport;
import com.dragee.modules.work.dto.PayInfoExport;
import com.dragee.modules.work.entity.JoinEntity;
import com.dragee.modules.work.entity.TrainEntity;
import com.dragee.modules.work.entity.TrainProjectEntity;
import com.dragee.modules.work.service.JoinService;
import com.dragee.modules.work.service.TrainProjectService;
import com.dragee.modules.work.service.TrainService;
import com.dragee.utils.LoginUserUtil;
import com.dragee.utils.excel.ExcelUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 培训
 *
 * @author tc
 * @email tc@mail.com
 * @date 2023-05-21 20:39:23
 */
@RestController
@RequestMapping("work/train")
@Api(tags = "培训")
public class TrainController {
    @Autowired
    private TrainService trainService;
    @Autowired
    private TrainProjectService trainProjectService;
    @Autowired
    private DicService dicService;
    @Autowired
    private UserService userService;
    @Autowired
    private JoinService joinService;

    /**
     * 列表
     */
    @GetMapping("list")
    @ApiOperation("培训列表")
    public R list(@RequestParam Map<String, Object> params){
        UserEntity user = userService.getById(LoginUserUtil.getLoginUserId());
        String province = user.getProvince();
        if (StrUtil.isNotBlank(province)) {
            params.put("province", province);
        }
        PageUtils page = trainService.queryPage(params);
        return R.ok().put("data", page);
    }

    /**
     * 信息c     */
    @GetMapping("getProjectsByTrainId")
    @ApiOperation("获取培训的项目列表")
    public R getProjectsByTrainId(@RequestParam("trainId") String trainId){
        List<TrainProjectEntity> projects = trainService.getProjectByTrain(trainId);
        return R.ok().put("data", projects);
    }


    /**
     * 信息
     */
    @GetMapping("{id}")
    @ApiOperation("培训详细信息")
    public R info(@PathVariable("id") Long id){
		TrainEntity train = trainService.getInfoById(id.toString());
        return R.ok().put("data", train);
    }


    /**
     * 保存
     */
    @PostMapping("saveOrUpdate")
    @ApiOperation("保存或修改培训")
    public R saveOrUpdate(@RequestBody TrainEntity train){

        trainService.saveOrUpdate(train);

        String groups = train.getGroups();
        String[] groupArr = groups.split(",");
        for (String s : groupArr) {
            DicEntity dic = dicService.getByChName(s);
            if (dic == null) {
                dic = new DicEntity("trainGroup", s);
                dicService.saveOrUpdate(dic);
            }
        }
        return R.ok();
    }


    /**
     * 删除
     */
    @GetMapping("delete-by-id")
    @ApiOperation("培训删除")
    public R delete( String id){
        trainService.removeById(Long.parseLong(id));
        trainProjectService.remove(new QueryWrapper<TrainProjectEntity>().eq("trainId", id));
        return R.ok();
    }

    @GetMapping("delete-by-ids")
    @ApiOperation("培训批量删除")
    public R deletes(String ids){
        String[] idArr = ids.split(",");
        Arrays.stream(idArr).forEach(id -> {
            trainService.removeById(Long.parseLong(id));
            trainProjectService.remove(new QueryWrapper<TrainProjectEntity>().eq("trainId", id));
        });

        return R.ok();
    }


    // ===============================================培训项目=======================================================
    // ===============================================培训项目=======================================================
    // ===============================================培训项目=======================================================

    /**
     * 保存
     */
    @PostMapping("project/saveOrUpdate")
    @ApiOperation("保存或修改项目")
    public R saveOrUpdate(@RequestBody TrainProjectEntity trainProjectEntity){
        if (StrUtil.isBlank(trainProjectEntity.getTrainId())) {
            throw new BusinessException(501, "需要传入培训的主键");
        }
        trainProjectService.saveOrUpdate(trainProjectEntity);

        // 设置字典
        String projectType = trainProjectEntity.getType();
        DicEntity projectTypeDic = dicService.getByChName(projectType);
        if (projectTypeDic == null) {
            projectTypeDic = new DicEntity("trainProjectType", projectType);
            dicService.saveOrUpdate(projectTypeDic);
        }
        String project = trainProjectEntity.getName();
        String enName = "trainProject-" + projectTypeDic.getId();
        DicEntity projectDic = dicService.getOne(new QueryWrapper<DicEntity>().eq("chName", project).eq("enName", enName), false);
        if (projectDic == null) {
            projectDic = new DicEntity(enName, project);
            dicService.saveOrUpdate(projectDic);
        }
        return R.ok();
    }


    /**
     * 删除
     */
    @GetMapping("project/delete-by-id")
    @ApiOperation("项目删除")
    public R projectDeleteById( String id){
        trainProjectService.removeById(Long.parseLong(id));
        return R.ok();
    }

    /**
     * 信息
     */
    @GetMapping("project/{id}")
    @ApiOperation("项目信息")
    public R projectInfo(@PathVariable("id") Long id){
        TrainProjectEntity competition = trainProjectService.getById(id);
        return R.ok().put("data", competition);
    }


    @GetMapping("getGroupDic")
    @ApiOperation("获取组别Dic")
    public R getGroupDic () {
        List<DicEntity> group = dicService.findDic("trainGroup");
        List<String> collect = group.stream().map(DicEntity::getChName).collect(Collectors.toList());
        return R.ok().put("data", collect);
    }

    @GetMapping("getTypeDic")
    @ApiOperation("获取大类Dic")
    public R getTypeDic () {
        List<DicEntity> group = dicService.findDic("trainProjectType");
        List<String> collect = group.stream().map(DicEntity::getChName).collect(Collectors.toList());
        return R.ok().put("data", collect);
    }

    @GetMapping("getProjectDic")
    @ApiOperation("获取小项Dic")
    public R getProjectDic (@RequestParam("type") String type) {
        DicEntity typeDic = dicService.getByChName(type);
        String enName =  "trainProject-" + typeDic.getId();
        List<DicEntity> dic = dicService.findDic(enName);
        List<String> collect = dic.stream().map(DicEntity::getChName).collect(Collectors.toList());
        return R.ok().put("data", collect);
    }

// ===========================================导出====================================
// ===========================================导出====================================
// ===========================================导出====================================
    @ApiOperation(value = "导出培训人员汇总表")
    @GetMapping("/exportJoinPerson")
    public void exportJoinPerson (@RequestParam("trainId") String trainId,
                               HttpServletResponse response ) throws Exception {
        TrainEntity train = trainService.getById(trainId);
        List<JoinEntity> applys = joinService.list(new QueryWrapper<JoinEntity>()
                .select("id")
                .eq("trainId", trainId));
        List<JoinPersonsExport> datas = new ArrayList<>();
        for (JoinEntity apply : applys) {
            JoinPersonsExport ex = new JoinPersonsExport();
            ex.setName(apply.getName());
            ex.setTel(apply.getTel());
            ex.setIdCard(apply.getIdCard());
            ex.setUnit(apply.getUnit());
            TrainProjectEntity project = trainProjectService.getById(apply.getProjectId());
            ex.setProjectName(project.getName());
            datas.add(ex);
        }
        ExcelUtils.writeExcel(response,
                datas,
                train.getName() + "-报名汇总表-" + System.currentTimeMillis(),
                "数据", PayInfoExport.class);
    }

    @ApiOperation(value = "导出缴费信息")
    @GetMapping("/exportPayInfo")
    public void exportPayInfo (@RequestParam("trainId") String trainId,
                               HttpServletResponse response ) throws Exception {
        TrainEntity train = trainService.getById(trainId);
        List<JoinEntity> applys = joinService.list(new QueryWrapper<JoinEntity>()
                .select("id")
                .eq("trainId", trainId));
        List<JoinPayInfoExport> datas = new ArrayList<>();
        for (JoinEntity apply : applys) {
            JoinPayInfoExport ex = new JoinPayInfoExport();
            ex.setName(apply.getName());
            ex.setTel(apply.getTel());
            ex.setIdCard(apply.getIdCard());
            ex.setWaitCost(apply.getCost() + "");
            ex.setUnit(apply.getUnit());
            ex.setFaPiaoShuiHao(apply.getInvoiceTitle());
            ex.setFaPiaoShuiHao(apply.getInvoiceTaxNumber());
            ex.setIsPay(apply.getStatus().equals("已通过") ? "是" : "否");
            datas.add(ex);
        }
        ExcelUtils.writeExcel(response,
                datas,
                train.getName() + "-缴费信息-" + System.currentTimeMillis(),
                "数据", PayInfoExport.class);
    }

}
